<template>
  <div class="home" id="app">
    <!-- 头部 -->
    <el-row type="flex" justify="space-between" align="middle">
      <el-col :span="12">
        <div class="logo">宸名小说</div>
      </el-col>
      <el-col :span="12">
        <el-menu mode="horizontal" class="header-menu">
          <el-menu-item index="1" @click="jumpToHomeView">首页</el-menu-item>
          <el-menu-item index="2" @click="jumpToBookStore">书库</el-menu-item>
          <el-menu-item index="3" @click="jumpToBookShelf">书架</el-menu-item> <!-- 添加书架页面链接 -->
          <el-menu-item index="4" @click="jumpToFriendPage"> 好友</el-menu-item>
          
        </el-menu>
      </el-col>
      <el-col :span="8">
        <el-input
          v-model="searchQuery"
          placeholder="搜索小说"
          class="search-input"
        ></el-input>
        <el-button type="primary" @click="searchNovels">搜索</el-button>
      </el-col>
     <!-- 新增：登录后显示的用户头像和用户名 -->
      <el-col :span="4" v-if="isLoggedIn">
      <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link user-dropdown-link">
            <img :src="userAvatar" class="user-avatar" />
            <span class="user-name">
              {{ userName }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="changeMessage">修改信息</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <!-- 新增：未登录时显示的登录和注册按钮 -->
      <el-col v-else :span="4">
        <el-button type="primary" @click="login">登录</el-button>
        <el-button @click="register">注册</el-button>
      </el-col>
    </el-row>
    <!-- 新增：修改信息对话框 -->
    <el-dialog
      :visible.sync="showChangeInfoDialog"
      title="修改信息"
      @close="resetChangeInfoForm"
    >
      <template>
        <el-form :model="changeInfoForm" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="changeInfoForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="changeInfoForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="头像">
            <div style="display: flex; align-items: center;">
              <img v-if="changeInfoForm.avatarUrl" :src="changeInfoForm.avatarUrl" class="user-avatar" style="width: 60px; height: 60px;" />
              <el-upload
              action="#"
              :show-file-list="false"
              :on-change="handleAvatarChange"
              >
                <el-button size="small" type="primary">选择文件</el-button>
              </el-upload>
            </div>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showChangeInfoDialog = false">取消</el-button>
          <el-button type="primary" @click="submitChangeInfoForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 新增：用户头像和用户名的样式 */
.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-name {
  font-size: 14px;
  color: #333;
}

/* 新增：下拉列表的样式 */
.user-dropdown-link {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-dropdown-link:hover {
  color: #66b1ff;
}

.el-dropdown-menu {
  min-width: 100px;
}

.el-dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
}

.el-dropdown-item:hover {
  background-color: #f5f7fa;
}
</style>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      searchQuery: "",
      isLoggedIn: false,
      userAvatar: require("../assets/logo.png"),
      userName: 'none',
      showChangeInfoDialog: false,
      changeInfoForm: {
        username: '',
        password: '',
        avatar: null, // 存储文件对象
        avatarUrl: '' // 存储文件的临时 URL
      }
    };
  },
  methods: {
    jumpToHomeView() {
      this.$router.push('/homeview');
    },
    jumpToBookStore() {
      this.$router.push('/bookstore');
    },
    jumpToBookShelf() {
      this.$router.push('/bookshelf'); // 添加跳转到书架页面的方法
    },
    jumpToFriendPage() {
      this.$router.push('/chatpage');
    },
    searchNovels() {
      // 在这里实现搜索功能
      this.$router.push({
        name: 'BookSearch',
        params: {
          searchQuery: this.searchQuery
        }
      });
    },
    login() {
      // 跳转到登录功能
      this.$router.push('/login');
    },
    register() {
      // 跳转注册功能
      this.$router.push('/register');
    },
    logout() {
      this.axios.get('/user/user/logout').then(res => {
        console.log(res.data);
        sessionStorage.removeItem('authentication');
        this.$router.push('/login'); // 跳转到登录页面
      })
      
    },
    handleCommand(command) {
      console.log(command);
      if (command === 'logout') {
        this.logout();
      } else if (command === 'changeMessage') {
        this.showChangeInfoDialog = true;
        // 初始化表单数据
        this.axios.get('/user/user/list').then(res => {
          this.changeInfoForm.username = res.data.data.username;
          this.changeInfoForm.avatarUrl = res.data.data.avatar;
        }).catch(error => {
          console.error('获取用户信息出错:', error);
        })   
      }
    },
    handleAvatarChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.changeInfoForm.avatarUrl = e.target.result;
      };
      reader.readAsDataURL(file.raw);
      this.changeInfoForm.avatar = file.raw; // 存储文件对象
    },
    submitChangeInfoForm() {
      const formData = new FormData();
      if (this.changeInfoForm.avatar) {
        formData.append('image', this.changeInfoForm.avatar);
      }

      // 先上传头像
      axios.post('/user/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        if (response.data.code === 1) { // 假设成功码是 200
          const avatarUrl = response.data.data;
          // 再提交用户名和密码及头像 URL
          axios.post('/user/user/update', {
            username: this.changeInfoForm.username,
            password: this.changeInfoForm.password,
            avatar: avatarUrl
          })
          .then(res => {
            if (res.data.code === 1) {
              this.$message.success('信息修改成功');
              this.userName = this.changeInfoForm.username;
              this.userAvatar = avatarUrl;
              this.showChangeInfoDialog = false;
              this.resetChangeInfoForm();
            } else {
              this.$message.error('信息修改失败');
            }
          })
          .catch(error => {
            console.error('信息修改出错:', error);
            this.$message.error('信息修改出错，请稍后重试');
          });
        } else {
          this.$message.error('头像上传失败');
        }
      })
      .catch(error => {
        console.error('头像上传出错:', error);
        this.$message.error('头像上传出错，请稍后重试');
      });
    },
    resetChangeInfoForm() {
      this.changeInfoForm = {
        username: '',
        password: '',
        avatar: null,
        avatarUrl: ''
      };
    },
    handleBeforeUnload(event) {
      // 在这里执行你需要的操作
      console.log('页面即将关闭，执行某些操作');
      this.logout();
      // 如果你需要阻止页面关闭，可以返回一个非空字符串
      // event.returnValue = '确定要离开吗？';
    }
  },
  beforeMount() {
    console.log('beforeMount');
    if (sessionStorage.getItem('authentication')) {
      this.isLoggedIn = true;
      this.userName = JSON.parse(sessionStorage.getItem('user')).username;
      this.userAvatar = JSON.parse(sessionStorage.getItem('user')).avatar;
      console.log(JSON.parse(sessionStorage.getItem('user')));
      console.log(this.userName);
    }
  },
  mounted() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy() {
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }
}
</script>

<style scoped>
.user-avatar {
  border-radius: 50%;
  margin-right: 10px;
}
.home {
  padding: 20px;
}

.logo {
  font-size: 24px;
  font-weight: bold;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}
</style>